package com.example.demo.controller;

import com.example.demo.entity.Goods;
import com.example.demo.service.GoodsService;
import com.example.demo.service.ShoppingCartService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/Goods")
public class GoodsController {
    private GoodsService goodsService;
    private ShoppingCartService shoppingCartService;

    // 获取所有商品
    @GetMapping("/all")
    public ResponseEntity<List<Goods>> getAllGoods() {
        List<Goods> goods = goodsService.getAllGoods();
        return ResponseEntity.ok(goods);
    }

    // 根据分类获取商品
    @GetMapping("/category/{category}")
    public ResponseEntity<List<Goods>> getGoodsByCategory(@PathVariable String category) {
        List<Goods> goods = goodsService.getGoodsByCategory(category);
        return ResponseEntity.ok(goods);
    }

    // 获取所有分类
    @GetMapping("/categories")
    public ResponseEntity<List<String>> getAllCategories() {
        List<String> categories = goodsService.getAllCategories();
        return ResponseEntity.ok(categories);
    }

    // 获取商品详情
    @GetMapping("/detail/{id}")
    public ResponseEntity<Goods> getGoodsDetail(@PathVariable Integer id) {
        Goods goods = goodsService.getGoodsById(id);
        if (goods == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        return ResponseEntity.ok(goods);
    }

    // 查看自己发布的商品
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Goods>> getUserGoods(@PathVariable Integer userId) {
        List<Goods> userGoods = goodsService.getUserGoods(userId);
        return ResponseEntity.ok(userGoods);
    }

    // 商品搜索
    @GetMapping("/search")
    public ResponseEntity<List<Goods>> searchGoods(@RequestParam String keyword) {
        List<Goods> result = goodsService.getAllGoods().stream()
                .filter(g -> g.getGName().contains(keyword) ||
                        g.getGDescription().contains(keyword))
                .collect(Collectors.toList());

        return ResponseEntity.ok(result);
    }

    // 创建订单/就是下单（点击商品，然后直接下单即可）
    // 用户如果下单自己发布的商品是不行的。
    @PostMapping("/create-order")
    public ResponseEntity<Map<String, Object>> createOrder(
            @RequestParam Integer userId,
            @RequestParam Integer goodsId,
            @RequestParam Integer quantity) {

        Map<String, Object> response = new HashMap<>();

        try {
            String result = goodsService.createOrder(userId, goodsId, quantity);
            response.put("success", true);
            response.put("message", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    // 添加到购物车
    @PostMapping("/add-to-cart")
    public ResponseEntity<Map<String, String>> addToCart(@RequestBody CartRequest request) {
        Map<String, String> response = new HashMap<>();
        try {
            String result = goodsService.addToCart(
                    request.getUserId(),
                    request.getGoodsId(),
                    request.getQuantity());
            response.put("message", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    // 添加 CartRequest 类来封装请求参数
    static class CartRequest {
        private Integer userId;
        private Integer goodsId;
        private Integer quantity;

        // 必须提供无参构造函数
        public CartRequest() {}

        // Getters 和 Setters
        public Integer getUserId() { return userId; }
        public void setUserId(Integer userId) { this.userId = userId; }

        public Integer getGoodsId() { return goodsId; }
        public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; }

        public Integer getQuantity() { return quantity; }
        public void setQuantity(Integer quantity) { this.quantity = quantity; }
    }

    @GetMapping("/cart-count/{goodsId}")
    public ResponseEntity<Integer> getCartCountForGoods(@PathVariable Integer goodsId) {
        int count = shoppingCartService.countCartAddsByGoodsId(goodsId);
        return ResponseEntity.ok(count);
    }

    @PostMapping("/create")
    public ResponseEntity<Goods> createGoods(@RequestBody Goods goods) {
        try {
            // 设置创建时间和状态
            goods.setGCreateTime(new Date());
            goods.setGIsActive(true);
            goods.setGIsTrade(false);

            Goods createdGoods = goodsService.createGoods(goods);
            return ResponseEntity.ok(createdGoods);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteGoods(@PathVariable Integer id) {
        try {
            goodsService.deleteGoods(id);
            return ResponseEntity.ok("商品删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("商品删除失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    public ResponseEntity<String> updateGoodsStatus(@PathVariable Integer id, @RequestParam Boolean active) {
        try {
            goodsService.updateGoodsStatus(id, active);
            return ResponseEntity.ok("商品状态更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("商品状态更新失败: " + e.getMessage());
        }
    }

    // 更新商品信息
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateGoods(@RequestBody Goods updatedGoods) {
        Map<String, Object> response = new HashMap<>();
        try {
            Goods goods = goodsService.updateGoods(updatedGoods);
            response.put("success", true);
            response.put("message", "商品信息更新成功");
            response.put("data", goods);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
}
